package com.finance.framework.shiro;

import com.finance.system.bean.pojo.User;
import com.finance.system.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/****
 * shiro 认证 需要登录
 * @author Administrator
 *
 */
@Component
public class CustomRolesAuthorizationFilter extends AuthorizationFilter {
	@Resource
	private IUserService userService;
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		if(mappedValue==null) {
            return false;
        }
		String[] rolesArray = (String[]) mappedValue;
		if(rolesArray.length==0) {
            return false;
        }
		Subject currentUser = SecurityUtils.getSubject();
		User user = (User)currentUser.getSession().getAttribute("authUser");

		if(user==null) {
            return false;
        }
		for(String roleId : rolesArray){
			if(this.userService.hasRole(user,roleId)) {
                return true;
            }
		}
		return false;
	}
}